package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class QuanziService {
//    寻找从mongodb中找数据的dubbo的接口
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
//    负责token校验
    @Autowired
    private UserService userService;
//    找用户的信息
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PicUploadService picUploadService;


    public PageResult queryPublishList(Integer page, Integer pageSize) {
        //分析：通过dubbo中的服务查询用户的好友动态
        //通过mysql查询用户的信息，回写到结果对象中（QuanZiVo）
//        前台需要一个一个这样的对象集合
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

//       开始校验token，token中包括了user对象的属性
//        直接从UserThreadLocal得到user对象
        User user = UserThreadLocal.get();

//        通过dubbo来查询数据(需要用户id和页数和pagesize)用来装mongodb中的数据
        PageInfo<Publish> pageInfo = this.quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        ArrayList<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(
                publish -> {
                    QuanZiVo quanZiVo = new QuanZiVo();
//                   toHexString()--以十六进制的无符号整数形式返回一个整数参数的字符串表示形式。比如170返回的话就是aa。
                    quanZiVo.setId(publish.getId().toHexString());
                    quanZiVo.setTextContent(publish.getText());
                    quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
                    quanZiVo.setUserId(publish.getUserId());
                    quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                    quanZiVoList.add(quanZiVo);
                    });
//        查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList=this.userInfoService.queryUserInfoByUserIdList(userIds);
//        循环两个集合的数据来判断id是否相等，相等则填充数据（先循环大集合）
       for(QuanZiVo quanZiVo :quanZiVoList){
//            找到对应的需要返回到前台的数据
           for(UserInfo userInfo:userInfoList){
               if(quanZiVo.getUserId().longValue()==userInfo.getUserId().longValue()){
                   this.fillUserInfoToQuanZiVo(userInfo,quanZiVo);
               }
           }
       }
       pageResult.setItems(quanZiVoList);
       return pageResult;
    }
//  用来将一个对象注入另一个对象中
    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

        //当前用户
        User user = UserThreadLocal.get();

        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
        quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //点赞数
        quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(quanZiVo.getId()))); //喜欢数
    }

    /**/
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        //分析：通过dubbo中的服务查询系统推荐动态
        //通过mysql查询用户的信息，回写到结果对象中（QuanZiVo）

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //直接从ThreadLocal中获取对象
        User user = UserThreadLocal.get();

        //通过dubbo查询数据
        PageInfo<Publish> pageInfo = this.quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        pageResult.setItems(this.fillQuanZiVo(records));
        return pageResult;
    }


    /**
     * 根据查询到的publish集合填充QuanZiVo对象
     *
     * @param records
     * @return
     */
    private List<QuanZiVo> fillQuanZiVo(List<Publish> records){
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        });

        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if(quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()){
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        return quanZiVoList;
    }


    public boolean savePublish(String textContent, String location, String latitude, String longitude, MultipartFile[] multipartFile) {
//        查询当前的登录信息
        User user = UserThreadLocal.get();

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);
        ArrayList<String> picUrls = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            picUrls.add(picUploadResult.getName());
        }
        publish.setMedias(picUrls);
        return this.quanZiApi.savePublish(publish);
    }

    /**
     * 点赞评论的业务层
     * @param publishId
     * @return
     */
    public Long likeComment(String publishId) {
//        根据token查询user对象
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.likeComment(user.getId(), publishId);
        if (result){
//            查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    /**
     * 取消点赞
     * @param publishId
     * @return
     */
    public Long disLikeComment(String publishId){
        User user = UserThreadLocal.get();
//        取消点赞
        Boolean result = this.quanZiApi.disLikeComment(user.getId(), publishId);
        if (result){
//            查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
//        如果没有点赞的话直接返回null意思本来就没有点赞
        return null;
    }


//    需要重新理解
    private void filluserInfoToQuanZivo(UserInfo userInfo,QuanZiVo quanZiVo){

            BeanUtil.copyProperties(userInfo, quanZiVo, "id");
            quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
            quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

            //当前用户
            User user = UserThreadLocal.get();

            quanZiVo.setCommentCount(0); //TODO 评论数
            quanZiVo.setDistance("1.2公里"); //TODO 距离
            quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
            quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //点赞数
            quanZiVo.setHasLoved(0); //TODO 是否喜欢（1是，0否）
            quanZiVo.setLoveCount(0); //TODO 喜欢数
        }
//      ========================================
//    喜欢和不喜欢
    public Long loveComment(String publishId) {
    User user = UserThreadLocal.get();
    //喜欢
    Boolean result = this.quanZiApi.loveComment(user.getId(), publishId);
    if(result){
        //查询喜欢数
        return this.quanZiApi.queryLoveCount(publishId);
    }
    return null;
}

    public Long disLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        //取消喜欢
        Boolean result = this.quanZiApi.disLoveComment(user.getId(), publishId);
        if(result){
            //查询喜欢数
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }
//==========================
//    查询单个
    public QuanZiVo queryById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
            }
    return this.fillQuanZiVo(Arrays.asList(publish)).get(0);
    }
}


